package com.chookss.home.search;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.mine.entity.MineNavigationEntity;
import com.chookss.tiku.view.FlowLayout;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionSpUtils;
import com.chookss.tools.Utils;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import scut.carson_ho.searchview.EditText_Clear;

public class SearchRecordActivity extends BaseAct {


    @BindView(R.id.et_search)
    EditText_Clear etSearch;
    @BindView(R.id.search_cancle)
    TextView searchCancle;
    @BindView(R.id.llvDelele)
    LinearLayout llvDelele;
    @BindView(R.id.llHistory)
    LinearLayout llHistory;
    @BindView(R.id.llEmpty)
    LinearLayout llEmpty;
    @BindView(R.id.tvEmpty)
    TextView tvEmpty;
    @BindView(R.id.ivEmpty)
    ImageView ivEmpty;
    @BindView(R.id.flowLayout)
    FlowLayout flowLayout;
    @BindView(R.id.rvView)
    RecyclerView rvView;
    private List<String> lists = new ArrayList<>();
    private FlowAdapter adapter;
    private String key = "";
    private boolean isMore=false;//默认是不展示更多的
    private Drawable drawableDown=null,drawableUp=null;
    private List<MineNavigationEntity> searchRecordTopLists=new ArrayList<>();
    private List<MineNavigationEntity> searchRecordBottomLists=new ArrayList<>();
    private List<MineNavigationEntity> searchRecordLists=new ArrayList<>();
    private SearchRecordAdapter searchRecordAdapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_record);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        tvEmpty.setText("暂无搜索记录");
        ivEmpty.setBackgroundResource(R.drawable.icon_default_no_search);
        drawableDown = ContextCompat.getDrawable(this,R.drawable.ico_down);
        drawableUp = ContextCompat.getDrawable(this,R.drawable.ico_up);
        drawableDown.setBounds(0,0, Utils.dip2px(this,40),  Utils.dip2px(this,40));
        drawableUp.setBounds(0,0,  Utils.dip2px(this,40),  Utils.dip2px(this,40));
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        add(v.getText().toString());
                        key = v.getText().toString();
                        Utils.hideInputKeyboard(SearchRecordActivity.this, etSearch);
                        Intent intent=new Intent(SearchRecordActivity.this, MySearchActivity.class);
                        intent.putExtra("key",key);
                        startActivity(intent);
                        finish();
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入关键词");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(searchCancle==null){
                    return;
                }
                if(Utils.isNull(etSearch.getText().toString())){
                    searchCancle.setText("取消");
                }else{
                    searchCancle.setText("搜索");
                }

            }
        });
        String text = new ShareUtils().getString(this,Utils.getCacheName(this,StaticClass.ALL_HISTORY), "");
        if (!Utils.isNull(text)) {
            List<String> stringList = JSONArray.parseArray(text, String.class);
            if (stringList != null) {
                lists.addAll(stringList);
            }
            if (lists.size() > 0) {
                // 设置 Adapter
                flowLayout.setVisibility(View.VISIBLE);
                adapter = new FlowAdapter(this, lists);
                flowLayout.setAdapter(adapter);
                llEmpty.setVisibility(View.GONE);
            }else{
                flowLayout.setVisibility(View.GONE);
                llEmpty.setVisibility(View.VISIBLE);
            }
        }else{
            flowLayout.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
        }
        GridLayoutManager gridLayoutManager3 = new GridLayoutManager(this, 5);
        rvView.setLayoutManager(gridLayoutManager3);
        searchRecordAdapter = new SearchRecordAdapter(R.layout.item_search_record, this, searchRecordLists);
        rvView.setAdapter(searchRecordAdapter);
        initAdapter();
    }
    private void initAdapter(){
        List<MineNavigationEntity> lists=new ArrayList<>();
        if(PermissionSpUtils.getBoolean(this,"13",false)) {
            MineNavigationEntity entity1 = new MineNavigationEntity();
            entity1.setLogo(R.drawable.icon_timu);
            entity1.setTitle("题目");
            lists.add(entity1);
        }
        if(PermissionSpUtils.getBoolean(this,"14",false)) {
            MineNavigationEntity entity2 = new MineNavigationEntity();
            entity2.setLogo(R.drawable.icon_xshipin);
            entity2.setTitle("小视频");
            lists.add(entity2);
            MineNavigationEntity entity3=new MineNavigationEntity();
            entity3.setLogo(R.drawable.icon_search_shipin);
            entity3.setTitle("视频");
            lists.add(entity3);
        }
        if(PermissionSpUtils.getBoolean(this,"04",false)){
            MineNavigationEntity entity4=new MineNavigationEntity();
            entity4.setLogo(R.drawable.icon_search_plan);
            entity4.setTitle("学习计划");
            lists.add(entity4);
        }

        if(PermissionSpUtils.getBoolean(this,"03",false)){
            MineNavigationEntity entity6=new MineNavigationEntity();
            entity6.setLogo(R.drawable.icon_ziolaio);
            entity6.setTitle("资料库");
            lists.add(entity6);
        }
        if(PermissionSpUtils.getBoolean(this,"02",false)){
            MineNavigationEntity entity7=new MineNavigationEntity();
            entity7.setLogo(R.drawable.icon_search_rizhi);
            entity7.setTitle("日志");
            lists.add(entity7);
        }
        MineNavigationEntity entity8=new MineNavigationEntity();
        entity8.setLogo(R.drawable.icon_xinwen);
        entity8.setTitle("新闻");
        lists.add(entity8);
        if(PermissionSpUtils.getBoolean(this,"01",false)){
            MineNavigationEntity entity9=new MineNavigationEntity();
            entity9.setLogo(R.drawable.icon_gonggg);
            entity9.setTitle("公告");
            lists.add(entity9);
        }
        if(PermissionSpUtils.getBoolean(this,"05",false)){
            MineNavigationEntity entity10=new MineNavigationEntity();
            entity10.setLogo(R.drawable.icon_search_kaoshi);
            entity10.setTitle("考试");
            lists.add(entity10);
        }
        if(PermissionSpUtils.getBoolean(this,"07",false)){
            MineNavigationEntity entity11=new MineNavigationEntity();
            entity11.setLogo(R.drawable.icon_tongxun);
            entity11.setTitle("通讯录");
            lists.add(entity11);
        }
        if(PermissionSpUtils.getBoolean(this,"06",false)){
            MineNavigationEntity entity12=new MineNavigationEntity();
            entity12.setLogo(R.drawable.iicon_ability);
            entity12.setTitle("面试");
            lists.add(entity12);
        }
        if(PermissionSpUtils.getBoolean(this,"17",false)){
            MineNavigationEntity entity13=new MineNavigationEntity();
            entity13.setLogo(R.drawable.icon_search_tuwen);
            entity13.setTitle("图文");
            lists.add(entity13);
        }
        if(PermissionSpUtils.getBoolean(this,"26",false)){
            MineNavigationEntity entity14=new MineNavigationEntity();
            entity14.setLogo(R.drawable.icon_search_gallery);
            entity14.setTitle("图库");
            lists.add(entity14);
        }
        if(lists.size()>5){
            MineNavigationEntity entity5=new MineNavigationEntity();
            entity5.setLogo(R.drawable.ico_down);
            entity5.setTitle("更多");
            lists.add(4,entity5);
            searchRecordTopLists.addAll(lists.subList(0,5));
            searchRecordBottomLists.addAll(lists.subList(5,lists.size()));
        }else{
            searchRecordTopLists.addAll(lists);
        }
        searchRecordLists.addAll(searchRecordTopLists);
        searchRecordAdapter.notifyDataSetChanged();
    }
    private void add(String data) {
        // 设置 Adapter
        if(flowLayout==null){
            return;
        }
        if (!lists.contains(data)) {
            lists.add(data);
            saveSearchHistory();
            // 设置 Adapter
            flowLayout.setVisibility(View.VISIBLE);
            adapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(adapter);
            llEmpty.setVisibility(View.GONE);
        }
    }

    private void remove(int position) {
        // 设置 Adapter
        if(flowLayout==null){
            return;
        }
        lists.remove(position);
        saveSearchHistory();
        // 设置 Adapter
        if (lists.size() > 0) {
            flowLayout.setVisibility(View.VISIBLE);
            adapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(adapter);
            llEmpty.setVisibility(View.GONE);
        } else {
            flowLayout.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
        }


    }


    private void saveSearchHistory() {
        if (lists.size() > 6) {
            lists.remove(0);
        }
        String text = JSON.toJSONString(lists);
        new ShareUtils().putString(this, Utils.getCacheName(this,StaticClass.ALL_HISTORY), text);
    }

    @OnClick({R.id.search_record_back, R.id.search_cancle, R.id.llvDelele})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_record_back:
                finish();
                break;
            case R.id.search_cancle:
                if(searchCancle==null){
                    return;
                }
                if(searchCancle.getText().toString().equals("取消")){
                    finish();
                }else{
                    Intent intent=new Intent(SearchRecordActivity.this, MySearchActivity.class);
                    intent.putExtra("key",etSearch.getText().toString());
                    startActivity(intent);
                    finish();
                }
                break;
            case R.id.llvDelele:
                if(flowLayout==null){
                    return;
                }
                new ShareUtils().putString(this,Utils.getCacheName(this,StaticClass.ALL_HISTORY), "");
                lists.clear();
                flowLayout.setVisibility(View.GONE);
                llEmpty.setVisibility(View.VISIBLE);
                break;
        }
    }

    class FlowAdapter extends FlowLayout.Adapter<FlowAdapter.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<String> mContentList;

        public FlowAdapter(Context mContext, List<String> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_search_list, parent, false);
//            // 给 View 设置 margin
            ViewGroup.MarginLayoutParams mlp = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
            int margin = Utils.dip2px(mContext, 6);
            mlp.setMargins(margin, margin, margin, margin);
            view.setLayoutParams(mlp);

            return new FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position));
            holder.ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    remove(position);
                }
            });
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    key = mContentList.get(position);
                    etSearch.setText(key);
                    Intent intent=new Intent(SearchRecordActivity.this, MySearchActivity.class);
                    intent.putExtra("key",key);
                    startActivity(intent);
                    finish();
                }
            });
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;
            ImageView ivDelete;

            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
                ivDelete = itemView.findViewById(R.id.ivDelete);
            }
        }
    }
    class SearchRecordAdapter extends BaseQuickAdapter<MineNavigationEntity, BaseViewHolderEx> {
        private Context mContext;

        public SearchRecordAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<MineNavigationEntity> data) {
            super(layoutResId, data);
            this.mContext = context;
               }

        @Override
        protected void convert(BaseViewHolderEx helper,MineNavigationEntity item) {
            TextView tvTitle = helper.getView(R.id.tvTitle);
            ImageView ivLogo = helper.getView(R.id.ivLogo);
            tvTitle.setText(item.getTitle());
            Glide.with(mContext).load(item.getLogo()).into(ivLogo);
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(SearchRecordActivity.this, MySearchActivity.class);

                    if(tvTitle.getText().toString().equals("题目")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","题目");
                        startActivity(intent);
                        finish();
                    }else if(tvTitle.getText().toString().equals("小视频")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","小视频");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("视频")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","视频");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("学习计划")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","学习计划");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("更多")){
                       if(searchRecordBottomLists.size()>0){
                           searchRecordLists.get(helper.getItemPosition()).setTitle("收起");;
                           searchRecordLists.get(helper.getItemPosition()).setLogo( R.drawable.ico_up);;
                           searchRecordLists.addAll(searchRecordBottomLists);
                           searchRecordAdapter.notifyDataSetChanged();
                       }
                    }else  if(tvTitle.getText().toString().equals("收起")){
                        searchRecordLists.get(helper.getItemPosition()).setTitle("更多");;
                        searchRecordLists.get(helper.getItemPosition()).setLogo( R.drawable.ico_down);;
                        searchRecordLists.clear();
                        searchRecordLists.addAll(searchRecordTopLists);
                        searchRecordAdapter.notifyDataSetChanged();

                    }else  if(tvTitle.getText().toString().equals("资料库")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","资料库");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("日志")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","日志");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("新闻")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","新闻");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("公告")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","公告");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("考试")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","考试");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("通讯录")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","通讯录");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("面试")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","面试");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("图文")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","图文");
                        startActivity(intent);
                        finish();
                    }else  if(tvTitle.getText().toString().equals("图库")){
                        intent.putExtra("key",etSearch.getText().toString());
                        intent.putExtra("typeName","图库");
                        startActivity(intent);
                        finish();
                    }
                }
            });
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (etSearch != null) {
            Utils.hideInputKeyboard(this, etSearch);
        }
    }
}
